package com.harmontronics.hanma.paas.paas.utils;

import cn.hutool.core.util.PageUtil;
import com.harmontronics.hanma.paas.paas.common.PageBase;
import org.flowable.common.engine.api.query.NativeQuery;
import org.flowable.common.engine.api.query.Query;
import org.flowable.task.api.NativeTaskQuery;
import org.flowable.task.api.Task;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.flowable.task.service.history.NativeHistoricTaskInstanceQuery;


import java.util.List;

/**
 * @author ldb
 */
public class FlowableQueryUtils {


    public static <T extends Query<?, ?>, V> PageBase<V> doQuery(Query<T, V> query, int pageNo, int pageSize) {
        List<V> list = query.listPage(PageUtil.getStart(pageNo, pageSize), pageSize);
        long count = query.count();
        PageBase<V> pageBase = new PageBase<>();
        pageBase.setPageNo(pageNo);
        pageBase.setPageSize(pageSize);
        pageBase.setTotalCount(count);
        pageBase.setData(list);
        pageBase.setTotalPage(PageUtil.totalPage((int) count, pageSize));
        return pageBase;
    }

    public static  PageBase<Task> doTaskQuery(NativeTaskQuery query, NativeTaskQuery countQuery,int pageNo, int pageSize) {
        List<Task> list = query.listPage(PageUtil.getStart(pageNo, pageSize), pageSize);
        long count = countQuery.count();
        return getPageBase(pageNo, pageSize, list, count);
    }

    public static  PageBase<HistoricTaskInstance> doHistoricTaskQuery(NativeHistoricTaskInstanceQuery query, NativeHistoricTaskInstanceQuery countQuery, int pageNo, int pageSize) {
        List<HistoricTaskInstance> list = query.listPage(PageUtil.getStart(pageNo, pageSize), pageSize);
        long count = countQuery.count();
        return getPageBase(pageNo, pageSize, list, count);
    }


    private static <T>PageBase<T> getPageBase(int pageNo, int pageSize, List<T> list, long count) {
        PageBase<T> pageBase = new PageBase<>();
        pageBase.setPageNo(pageNo);
        pageBase.setPageSize(pageSize);
        pageBase.setTotalCount(count);
        pageBase.setData(list);
        pageBase.setTotalPage(PageUtil.totalPage((int) count, pageSize));
        return pageBase;
    }
}
